<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Api\BaseController;
use App\Http\Requests\NoteRequest;
use App\Http\Resources\Note;
use App\Http\Resources\NoteCollection;
use App\Note as NoteModel;
use App\Repositories\NoteRepository;
use App\Scopes\StatusScope;
use App\Traits\BaseApiFunc;
use Auth;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;

class NoteController extends BaseController {

	use BaseApiFunc;

	protected $model, $page_size;

	public function __construct(NoteRepository $note) {
		parent::__construct();

		$this->model = $note;
		$this->page_size = config('blog.admin_page.common_page');
	}

	public function notes() {
		$list = Cache::remember('notes', 30, function () {
			return $this->model->getNotes();
		});
		return $this->response->withSuccess($list);
	}

	public function store(NoteRequest $request) {
		$this->model->store(array_merge(['user_id' => Auth::user()->id], $request->all()));
		return $this->response->withNoContent();
	}

	public function note($id) {
		$note = $this->getResource($this->model->getById($id)->load('records'))->type('record');
		return $this->response->withSuccess($note);
	}

	public function completeNote($id) {
		$note = $this->getResource($this->model->getById($id)->load(['records' => function ($query) {
			return $query->withoutGlobalScope(StatusScope::class);
		}]))->type('complete');
		return $this->response->withSuccess($note);
	}

	protected function getResourceCollection(Collection $collection) {
		return new NoteCollection($collection);
	}

	protected function getResource(NoteModel $collection) {
		return new Note($collection);
	}

}
